import { dingConfig } from 'dingtalk-app';
import * as fs from 'fs';
import * as Koa from 'koa';
import evn from './config/env';
import log4jsConfig from './config/log4j.json';
import dTalkApi from './core/dTalkApi';
import finalHandler from './lib/middlewares/finalHandler';
import syncDataService from './services/syncDataService';
const bodyParser = require('koa-bodyparser');
const logger = require('koa-logger');
const views = require('koa-views');
const convert = require('koa-convert');
const serve = require('koa-static');
let log4js = require('koa-log4');
const app = new Koa();

let appenders: any[] = log4jsConfig.appenders;
if (!fs.existsSync(evn.logPath)) {
    fs.mkdirSync(evn.logPath);
}
appenders.forEach(value => {
    let filename: string = value.filename;
    let path: string = null;
    if (filename) {
        path = filename.substring(0, filename.lastIndexOf("/"));
    }
    if (value.filename && !fs.existsSync(path)) {
        fs.mkdirSync(path);
    }
});
app.use(finalHandler());
app.use(views(`${__dirname}/views`, {
    map: {
        html: 'nunjucks'
    }
}));
if (!fs.existsSync(evn.logPath)) {
    fs.mkdirSync(evn.logPath);
}
appenders.forEach(value => {
    let filename: string = value.filename;
    let path: string = '';
    if (filename) {
        path = filename.substring(0, filename.lastIndexOf("/"));
    }
    if (value.filename && !fs.existsSync(path)) {
        fs.mkdirSync(path);
    }
});
app.use(log4js.koaLogger(log4js.getLogger("access"), { level: 'auto' }));
app.use(logger());
app.use(bodyParser());
app.keys = ['some secret hurr'];
app.use(serve(__dirname + '/public'));
dingConfig.init(app, evn, [/^\/api\/*/])
let files = fs.readdirSync('./routers')
files.map(item => {
    console.log(`./routers/${item.substr(0, item.indexOf('.'))}`);
    const router: any = require(`./routers/${item.substr(0, item.indexOf('.'))}`)
    app.use(router.default.routes())
});

// syncDataService.run2().then(()=>{
//     console.log('定时任务!!!')
// })

export default app;

